<template>
  <div class="app-container">
    <!-- BOM -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="产品名称" prop="productName">
              <el-select
                v-model="queryParams.parentCode"
                placeholder="请选择产品名称"
                class="!w-[192px]"
                clearable
                filterable
                @change="handleQuery"
                @visible-change="getParentCode"
              >
                <el-option
                  v-for="item in optionsProductName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="datetimerange"
                placeholder="选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
                @change="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                icon="plus"
                @click="handleEdit({}, 'add')"
                v-hasPerm="'sys:productBom:edit'"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData">
            <el-table-column prop="parentName" label="产品名称" align="center" />
            <el-table-column prop="productName" label="物料名称" align="center" />
            <el-table-column prop="dosageQty" label="用量" align="center">
              <template #default="scope">
                <div>
                  {{ scope.row.dosageQty }}
                  {{ unitFormat(scope.row.unit) }}
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="lossQty" label="损耗数量(KG)" align="center" /> -->
            <el-table-column
              prop="lossRate"
              label="损耗率"
              align="center"
              :formatter="formatLossRate"
            />
            <!-- <el-table-column prop="unit" label="单位(KG)" align="center" /> -->
            <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleEdit(scope.row, 'edit')"
                  v-hasPerm="'sys:productBom:edit'"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDel(scope.row)"
                  v-hasPerm="'sys:productBom:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="产品名称" class="!mb-2" prop="parentName">
          <el-select
            v-model="dialogParams.parentName"
            placeholder="请选择产品名称"
            clearable
            filterable
            class="!w-44"
            @visible-change="getProductType"
            @change="changeparentName"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料名称" class="!mb-2" prop="productName">
          <el-select
            v-model="dialogParams.productName"
            placeholder="请选择物料名称"
            clearable
            filterable
            class="!w-44"
            @visible-change="getProduct"
            @change="changeproductName"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label=" " class="!flex !mb-2 !color-coolGray" prop="">
          ps：生产1单位产品需要原材料用量{{ dialogParams.dosageQty
          }}{{ `（${unitValue?.label || ""}）` }}
        </el-form-item>
        <!-- <div class="text-align-left ml-24 color-coolGray">
          
        </div> -->
        <el-form-item :label="`原材料用量（${unitValue?.label || ''}）`" prop="dosageQty">
          <el-input-number
            v-model="dialogParams.dosageQty"
            class="!w-44"
            placeholder="请输入原材料用量"
            clearable
          />
        </el-form-item>
        <el-form-item label="损耗率（%）" prop="lossRate">
          <el-input-number
            :min="0"
            :max="100"
            v-model="dialogParams.lossRate"
            placeholder="请输入损耗率"
            class="!w-44"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item label="损耗数量" prop="lossQty">
          <el-input-number
            disabled
            :model-value="dialogParams.dosageQty * (dialogParams.lossRate / 100)"
            placeholder="请输入损耗数量"
            class="!w-44"
            clearable
          />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark" class="w-full">
          <el-input
            v-noSpace
            v-model="dialogParams.remark"
            placeholder="请输入备注"
            clearable
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button v-debounce="submitDialog" type="primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import productBomAPI, { productBomPageQuery, productBomPageVO } from "@/api/productBom/productBom";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";
defineOptions({
  name: "User",
  inheritAttrs: false,
});

// 新增/修改弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});

const dialogParams = reactive({
  parentName: "",
  parentCode: "",
  productName: "",
  productCode: "",
  dosageQty: 0,
  lossQty: 0,
  lossRate: 0,
  unit: "",
  remark: "",
  productType: "",
});

const dialogFormRef = ref(ElForm);

const validateProductAndMaterialName = (rule: any, value: string, callback: Function) => {
  const parentName = (dialogParams as any).parentName;
  const productName = (dialogParams as any).productName;

  if (parentName && productName && parentName === productName) {
    callback(new Error("产品名称和物料名称不能相同"));
  } else {
    callback();
  }
};

const rules = reactive<Record<string, FormItemRule[]>>({
  parentName: [
    { required: true, message: "请输入产品名称", trigger: "blur" },
    { validator: validateProductAndMaterialName, trigger: "blur" },
  ],
  productName: [
    { required: true, message: "请输入物料名称", trigger: "change" },
    { validator: validateProductAndMaterialName, trigger: "blur" },
  ],
  dosageQty: [
    { required: true, message: "用量是必填项", trigger: "blur" },
    { type: "number", message: "用量必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "用量必须大于等于0", trigger: "blur" },
  ],
  lossQty: [
    { required: true, message: "损耗数量是必填项", trigger: "blur" },
    { type: "number", message: "损耗数量必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "损耗数量必须大于等于0", trigger: "blur" },
  ],
  lossRate: [
    { required: true, message: "损耗率是必填项", trigger: "blur" },
    { type: "number", message: "损耗率必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "损耗率必须大于等于0", trigger: "blur" },
  ],
  unit: [{ required: true, message: "请输入单位", trigger: "change" }],
});

const queryFormRef = ref(ElForm);

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const productOptions = ref<{ value: string; label: string; unit: string }[]>([]); // 显式指定类型

const optionsProductName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const queryParams = reactive<productBomPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<productBomPageVO[]>();
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
function handleQuery() {
  loading.value = true;
  productBomAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 合计
function handleTotal() {
  loading.value = true;
  console.log("queryParams", queryParams);
  productBomAPI
    .getTotal(queryParams)
    .then((data) => {
      console.log("data", data);
      listTotal.value = data?.qtyTotal ?? 0;
      // pageData.value = [...(data?.list as any)];
      // total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.parentCode = undefined;
  queryParams.timeScopes = undefined;
  handleQuery();
}

//重置弹窗
function clearDialogFormData() {
  let data = {
    parentName: "",
    parentCode: "",
    productName: "",
    productCode: "",
    dosageQty: 0,
    lossQty: 0,
    lossRate: 0,
    unit: "",
    remark: "",
    id: "",
    productType: "",
  };

  Object.assign(dialogParams, { ...data });
}

//新增/修改
function handleEdit(row: any, type: any) {
  dialog.type = type;
  if (type == "edit") {
    dialog.title = "编辑";
    Object.assign(dialogParams, { ...row });
    unitValue.value = unitOptions.value.find((item) => item.value === dialogParams.unit) as any;
  } else {
    dialog.title = "新增";
    clearDialogFormData();
  }
  dialog.visible = true;
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      productBomAPI
        .delDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}
//关闭弹窗
function handleCloseDialog() {
  dialogFormRef.value?.clearValidate();
  dialogFormRef.value?.resetFields();
  dialog.visible = false;
  unitValue.value = {};
}

// 提交弹窗
function submitDialog() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    let paramsData = <any>{};
    if (dialog.title == "新增") {
      paramsData = {
        parentName: dialogParams.parentName,
        parentCode: dialogParams.parentCode,
        productName: dialogParams.productName,
        productCode: dialogParams.productCode,
        dosageQty: dialogParams.dosageQty,
        lossQty: dialogParams.lossQty,
        lossRate: dialogParams.lossRate,
        unit: unitValue.value.value,
        remark: dialogParams.remark,
        productType: dialogParams.productType,
      };
    } else {
      paramsData = { ...dialogParams };
    }
    // paramsData.unit
    productBomAPI
      .submitDialog(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
        clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

const getProductType = async () => {
  try {
    const response = await productBomAPI.getTypePage({
      pageNum: 1,
      pageSize: 999,
      productType: "1",
    });
    const dataList = response?.list || [];

    options.value = dataList.map((item: any) => ({
      value: item.code,
      label: item.productName,
    }));
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};

const getProduct = () => {
  productBomAPI
    .getTypePage({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      productOptions.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
        unit: item.unit,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

function changeparentName(val: any) {
  dialogParams.parentCode = val.value;
  dialogParams.parentName = val.label;
}
function changeproductName(val: any) {
  dialogParams.productCode = val.value;
  dialogParams.productName = val.label;
  unitValue.value = unitOptions.value.find((item) => item.value === val.unit) as any;
}

const getParentCode = () => {
  productBomAPI
    .parentCod({ pageNum: 1, pageSize: 999, productType: "1" })
    .then((data) => {
      optionsProductName.value = (data?.list as any).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .catch((err: any) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 定义格式化函数
function formatLossRate(row: any, column: any, cellValue: any) {
  // return `${(cellValue * 100).toFixed(2)}%`; // 假设损耗率是小数形式，乘以100并保留两位小数
  return `${cellValue.toFixed(2)}%`;
}

onMounted(() => {
  handleQuery();
  getUnitList();
  // handleTotal();
});
</script>

<style lang="scss" scoped></style>
